package com.onpositive.image.factories;
import java.awt.Rectangle;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

import com.onpositive.image.fitting.tools.TransformerFactory;
import com.onpositive.image.fitting.tools.TransformerFactory.TransformParam;


public abstract class AbstractImageFitter {
	
	public BufferedImage fitImage( BufferedImage source , Rectangle destRect ){
		
		if( !checkFit( source, destRect ) )		
			return doFitImage( source, destRect );
		else
			return copy( source );
	}

	public BufferedImage fitImage( BufferedImage source , int width, int height )
	{
		Rectangle destRect = new Rectangle(width, height);
		if( !checkFit( source, destRect ) )		
			return doFitImage( source, destRect );
		else
			return copy( source ); 
	}
	
	
	protected abstract BufferedImage doFitImage( BufferedImage source , Rectangle destRect ) ;
	
	
	private boolean checkFit(BufferedImage source, Rectangle destRect) {
		
		int srcWidth = source.getWidth() ;
		int srcHeight = source.getHeight() ;
		
		boolean hLess = srcHeight < destRect.height;
		boolean wLess = srcWidth < destRect.width;
		boolean wEq = srcWidth == destRect.width;
		boolean hEq = srcHeight == destRect.height;
		
		return ( ( hLess && wEq ) || ( wLess && hEq ) || ( wEq && hEq ) ) ;

	}
	
	private BufferedImage copy( BufferedImage source )
	{
		AffineTransformOp tp = TransformerFactory.getInstance().getIdentityTransform() ;
		BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), source.getType() ) ;
		tp.filter( source, result ) ;
		
		return result;
	}

	
}
